package com.awesome.media;

import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.Surface;

import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.ext.rtmp.RtmpDataSourceFactory;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import com.google.android.exoplayer2.video.VideoListener;

/**
 * Author: JFangZ
 * Email:janezhang1901@163.com
 * Date: 2020/4/29 14:24
 * Description:Exo 引擎的播放器
 */
public class JeejioExoPlayer extends AbsPlayer {
    private final SimpleExoPlayer mSimpleExoPlayer;

    public JeejioExoPlayer(Context context) {
        super(context);
        mSimpleExoPlayer = new SimpleExoPlayer.Builder(context).build();
        mSimpleExoPlayer.addListener(new Player.EventListener() {

            @Override
            public void onIsPlayingChanged(boolean isPlaying) {
                Log.i(TAG, "onIsPlayingChanged" + " : " + "isPlaying--->" + isPlaying);
            }

            @Override
            public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
                Log.i(TAG, "onPlayerStateChanged" + " : "
                        + "playWhenReady--->" + playWhenReady
                        + ",playbackState--->" + playbackState
                );
                if (!playWhenReady && playbackState == Player.STATE_BUFFERING) {
                    // 开始缓冲,是不是就表示播放源可用,播放器已经准备好了呢
                    if (mMediaPlayerListener != null) {
                        mMediaPlayerListener.onPrepared();
                    }
                }
                if (playbackState == Player.STATE_BUFFERING) {
                    if (mMediaPlayerListener != null) {
                        mMediaPlayerListener.onBufferingStart();
                    }
                }
                if (playWhenReady && playbackState == Player.STATE_READY) {
                    if (mMediaPlayerListener != null) {
                        mMediaPlayerListener.onBufferingEnd();
                    }
                    if (mMediaPlayerListener != null && mSurface != null) {
                        mMediaPlayerListener.onVideoRenderingStart();
                    }
                }
                if (playWhenReady && playbackState == Player.STATE_ENDED) {
                    mSimpleExoPlayer.setPlayWhenReady(false);
                    if (mMediaPlayerListener != null) {
                        mMediaPlayerListener.onComplete();
                    }
                }
            }

            @Override
            public void onPlayerError(ExoPlaybackException error) {
                Log.e(TAG, "onPlayerError" + " : "
                        + "error--->" + error);
                if (mMediaPlayerListener != null) {
                    mMediaPlayerListener.onError(error);
                }
            }
        });
        mSimpleExoPlayer.addVideoListener(new VideoListener() {
            @Override
            public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) {
                if (mMediaPlayerListener != null) {
                    mMediaPlayerListener.onVideoSizeChanged(width, height);
                }
            }
        });
    }

    @Override
    public void setDisplay(Surface surface) {
        mSimpleExoPlayer.setVideoSurface(mSurface = surface);
    }

    @Override
    public void play(Uri uri) {
        mSimpleExoPlayer.stop(true);
        mSimpleExoPlayer.setPlayWhenReady(false);
        String userAgent = Util.getUserAgent(mContext, "QinshouBox");
        DataSource.Factory dataSourceFactory;
        MediaSource mediaSource = null;
        if (TextUtils.isEmpty(uri.getScheme())) {
            dataSourceFactory = new DefaultDataSourceFactory(mContext, userAgent);
            mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
                    .createMediaSource(uri);
        } else {
            if (TextUtils.equals("rtmp", uri.getScheme())) {
                // rtmp
                dataSourceFactory = new RtmpDataSourceFactory();
                mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
                        .createMediaSource(uri);
            } else if (TextUtils.equals("http", uri.getScheme()) || TextUtils.equals("https", uri.getScheme())) {
                dataSourceFactory = new DefaultHttpDataSourceFactory(userAgent);
                if (uri.toString().endsWith("m3u8")) {
                    // m3u8
                    mediaSource = new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
                } else {
                    mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
                            .createMediaSource(uri);
                }
            }
        }
        if (mediaSource == null) {
            if (mMediaPlayerListener != null) {
                mMediaPlayerListener.onError(new Exception("mediaSource is null"));
            }
        }
        mSimpleExoPlayer.prepare(mediaSource);
    }

    @Override
    public void start() {
        if (mSimpleExoPlayer.getPlaybackState() == Player.STATE_ENDED) {
            mSimpleExoPlayer.seekToDefaultPosition();
        }
        mSimpleExoPlayer.setPlayWhenReady(true);
    }

    @Override
    public void pause() {
        mSimpleExoPlayer.setPlayWhenReady(false);
    }

    @Override
    public void stop() {
        mSimpleExoPlayer.stop(true);
    }


    @Override
    public void reset() {
        mSimpleExoPlayer.setPlayWhenReady(false);
        mSimpleExoPlayer.retry();
    }

    @Override
    public void release() {
        mSimpleExoPlayer.release();
    }

    @Override
    public void seekTo(long position) {
        mSimpleExoPlayer.seekTo(position);
    }

    @Override
    public boolean isPlaying() {
        return mSimpleExoPlayer.isPlaying();
    }

    @Override
    public long getCurrentPosition() {
        return mSimpleExoPlayer.getCurrentPosition();
    }

    @Override
    public long getDuration() {
        return mSimpleExoPlayer.getDuration();
    }

    @Override
    public int getAudioSessionId() {
        return mSimpleExoPlayer == null ? -1 : mSimpleExoPlayer.getAudioSessionId();
    }

    @Override
    public int getVideoWidth() {
        Format format = mSimpleExoPlayer.getVideoFormat();
        if (format == null) {
            return 0;
        }
        return format.width;
    }

    @Override
    public int getVideoHeight() {
        Format format = mSimpleExoPlayer.getVideoFormat();
        if (format == null) {
            return 0;
        }
        return format.height;
    }

    @Override
    public void setVolume(float volume) {
        mSimpleExoPlayer.setVolume(volume);
    }

    @Override
    public void setSpeed(float speed) {
        PlaybackParameters playbackParameters = mSimpleExoPlayer.getPlaybackParameters();
        mSimpleExoPlayer.setPlaybackParameters(new PlaybackParameters(speed, playbackParameters.pitch, playbackParameters.skipSilence));
    }

    @Override
    public float getSpeed() {
        return mSimpleExoPlayer.getPlaybackParameters().speed;
    }

    public SimpleExoPlayer getSimpleExoPlayer() {
        return mSimpleExoPlayer;
    }
}